<template>
  <PageDialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="dialog-table">
      <PageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-button>
          <div class="dialog-table-header">
            <div class="header-left">
              <div class="lable">产品名称：{{ info.commonName }}</div>
              <div class="lable">生产批号：{{ info.batchNumber }}</div>
            </div>
            <div class="header-right">
              <div class="scan-groups">
                <el-input
                  v-model="filterInfo.query.uniqueCodeLike"
                  :clearable="true"
                  placeholder="请输入个体码"
                  @keyup.enter.native="search"
                  @input="(e) => (filterInfo.query.uniqueCodeLike = validSe(e))"
                ></el-input>
                <el-button style="margin-left: 10px" @click="search"
                  >搜索</el-button
                >
              </div>
            </div>
          </div>
          <div class="dialog-table-header">
            <div></div>
            <div>
              <el-button
                :disabled="!tableInfo.selections.length"
                @click="setPrintQty"
                >设置最大打印数量</el-button
              >
              <el-button
                :disabled="!tableInfo.selections.length"
                @click="printQrCode"
                >打印二维码</el-button
              >
            </div>
          </div>
        </template>
      </PageFilter>
      <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
        <DialogTable
          :refresh="tableInfo.refresh"
          ref="IndividualMultipleTable"
          :init-curpage="tableInfo.initCurpage"
          v-model:data="tableInfo.data"
          :api="api"
          :pager="false"
          :check-box="true"
          :tab-index="false"
          :listen-height="false"
          v-model:query="filterInfo.query"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
          @handleEvent="handleEvent"
        >
          <template v-slot:col-printQty="scope">
            <el-form-item
              v-if="scope.row.codeType === 1 || scope.row.codeType === 4"
              :prop="`data.${scope.$index}.printQty`"
              :rules="
                scope.$index >= 0
                  ? [
                      {
                        validator: $validate.naturalnumber,
                        trigger: 'blur,change',
                      },
                    ]
                  : []
              "
            >
              <el-input-number
                v-model="scope.row.printQty"
                :precision="0"
                :min="1"
                :max="maxPrintQty(scope.row)"
                @change="changePringQty(scope.row)"
                controls-position="right"
              ></el-input-number>
            </el-form-item>
            <span v-else>
              {{ scope.row.printQty }}
            </span>
          </template>
        </DialogTable>
      </el-form>
    </div>
  </PageDialog>
</template>

<script setup name="IndividualDetails">
import { getDepotStorageExtPost } from '@/api/stock'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  api: {
    type: Function,
    default: getDepotStorageExtPost,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
  callback: {
    type: Object,
    default: function () {
      return undefined
    },
  },
})
const selectedScanValue = ref('1')
const scanInput = ref('')
const filterInfo = ref({
  query: {
    sort: 'id',
    curPage: 1,
    pageSize: 99999,
    ...props.query,
  },
  list: [{ type: 'slot', value: 'button' }],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '个体码', value: 'uniqueCode' },
    { label: '二维码', value: 'qrCode' },
    { label: '原厂主码', value: 'factoryMainCode' },
    { label: '原厂从码', value: 'factorySubCode' },
    {
      label: '库存数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    { label: '打印数量', value: 'printQty', type: 'slot', minWidth: '160px' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '打印二维码',
        event: onPrintQRcode,
        show: true,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = ref({
  title: '个体详情',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const selectRow = ref('')
const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

onMounted(() => {
  setTimeout(() => {
    getList()
  }, 100)
})
function maxPrintQty(row) {
  let qty = row.qty ? row.qty : 1
  return Math.ceil(qty)
}
function setPrintQty() {
  tableInfo.value.selections.forEach((item) => {
    item.printQty = Math.ceil(item.qty)
    let row = tableInfo.value.data.find((el) => el.id === item.id)
    if (row && row.id) {
      row.printQty = item.printQty
    }
  })
  proxy.$nextTick(() => {
    proxy.$refs.tableForm.clearValidate()
  })
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  const _tableInfo = tableInfo.value
  _tableInfo.initCurpage = Math.random()
  _tableInfo.refresh = Math.random()
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function changePringQty(row) {
  if (tableInfo.value.selections.length) {
    tableInfo.value.selections.forEach((item) => {
      if (item.id === row.id) {
        item.printQty = row.printQty
      }
    })
  }
}
function handleSave() {
  shows.value = false
  // emits('callback', {
  //   table: props.info,
  //   selections: tableInfo.value.selections,
  // })
}
function printQrCode() {
  let selections = tableInfo.value.selections
  let items = selections.filter((item) => !item.printQty)
  if (items.length) {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      message: '当前所勾选的产品存在打印数量为空的情况，请处理',
      showClose: true,
    })
    return
  }
  emits('handlePrintQRcode', selections)
}
function onPrintQRcode(row) {
  if (!row.qrCode) {
    proxy.$message({
      message: '没有生成二维码，不能打印',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  if (!row.printQty) {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      message: '请输入打印数量',
      showClose: true,
    })
    return
  }
  emits('handlePrintQRcode', [row])
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
    case 'list':
      tableInfo.value.data = data.map((item) => {
        return {
          ...item,
          printQty:
            item.codeType === 2 || item.codeType === 3
              ? Math.ceil(item.qty)
              : 1,
        }
      })
      break
  }
}
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.scan-groups {
  display: flex !important;
  align-items: center;
}
</style>
